//
//  SEPrescriptionNewViewController.swift
//  SmartEyeForDoctor
//
//  Created by QDSG on 2021/5/10.
//

import UIKit

class SEPrescriptionNewViewController: SEBaseViewController {
    
    var updateHandler: (() -> Void)?
    
    private var viewModel = SEPrescriptionViewModel(prescription: SEPrescriptionModel())
    
    convenience init(mode: SEPrescriptionMode) {
        self.init()
        self.viewModel.prescriptionMode = mode
        self.title = mode.title
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadData()
        
        viewModel.updateData = { [weak self] status in
            switch status {
            case .success:
                self?.tableView.reloadData()
            case .auth:
                self?.presentLoginViewController(selector: #selector(self?.loadData))
            case .failure: break
            }
        }
        
        viewModel.confirmHandler = { [weak self, viewModel] status in
            switch status {
            case .success:
                SEHUD.show(message: viewModel.prescriptionMode.message)
                self?.updateHandler?()
                self?.navigationController?.popViewController(animated: true)
            case .auth:
                self?.presentLoginViewController(selector: #selector(self?.saveTapped))
            case .failure(let message):
                SEHUD.showError(message: message)
            }
        }
    }
    
    override func setupUI() {
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(UIScreen.navigationBarMaxY)
        }
    }
    
    @objc private func loadData() {
        viewModel.getDetail()
    }

    // MARK: - getter
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.backgroundColor = .background
        tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.height, height: 0.0001))
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        tableView.keyboardDismissMode = .onDrag
        tableView.delegate = self
        tableView.dataSource = self
        
        tableView.register(SEPrescriptionDiagnosisNewCell.nibForCell(),
                           forCellReuseIdentifier: SEPrescriptionDiagnosisNewCell.reuseIdentifier())
        tableView.register(SEPrescriptionRecommendNewCell.nibForCell(),
                           forCellReuseIdentifier: SEPrescriptionRecommendNewCell.reuseIdentifier())
        tableView.register(SEPrescriptionDrugsNewHeaderCell.nibForCell(),
                           forCellReuseIdentifier: SEPrescriptionDrugsNewHeaderCell.reuseIdentifier())
        tableView.register(SEPrescriptionDrugsNewCell.nibForCell(),
                           forCellReuseIdentifier: SEPrescriptionDrugsNewCell.reuseIdentifier())
        tableView.register(SEPrescriptionDrugsNewConfirmCell.nibForCell(),
                           forCellReuseIdentifier: SEPrescriptionDrugsNewConfirmCell.reuseIdentifier())
        
        return tableView
    }()
}

extension SEPrescriptionNewViewController {
    private func submitPrescription() {
        guard viewModel.templateNameNotEmpaty else {
            SEHUD.show(message: "请填写模板名称")
            return
        }
        
        guard viewModel.mainDiagnosisNotEmpty else {
            SEHUD.show(message: "请填写主诊断")
            return
        }
        
        guard viewModel.recommendNotEmpaty else {
            SEHUD.show(message: "请填写医生意见")
            return
        }
        
        guard viewModel.entrustNotEmpty else {
            SEHUD.show(message: "请填写用药嘱托")
            return
        }
        
        saveTapped()
    }
    
    @objc private func saveTapped() {
        viewModel.save()
    }
}

// MARK: - UITableViewDataSource

extension SEPrescriptionNewViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.numberOfSectionsForNew
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRowsForNew(in: section)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEPrescriptionDiagnosisNewCell.reuseIdentifier(),
                                                     for: indexPath) as! SEPrescriptionDiagnosisNewCell
            cell.delegate = self
            cell.update(with: viewModel, editEnable: viewModel.canEdit)
            return cell
        case 2:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEPrescriptionDiagnosisNewCell.reuseIdentifier(),
                                                     for: indexPath) as! SEPrescriptionDiagnosisNewCell
            cell.delegate = self
            cell.update(with: viewModel.subDiagnosisViewModel(at: indexPath), editEnable: viewModel.canEdit)
            return cell
        case 3:
            let cellType = SEPrescriptionRecommendNewCellType(rawValue: indexPath.row) ?? .recommend
            let cell = tableView.dequeueReusableCell(withIdentifier: SEPrescriptionRecommendNewCell.reuseIdentifier(),
                                                     for: indexPath) as! SEPrescriptionRecommendNewCell
            cell.update(with: viewModel, cellType: cellType)
            return cell
        case 4:
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: SEPrescriptionDrugsNewHeaderCell.reuseIdentifier(),
                                                         for: indexPath) as! SEPrescriptionDrugsNewHeaderCell
                cell.update(with: viewModel)
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: SEPrescriptionDrugsNewCell.reuseIdentifier(),
                                                         for: indexPath) as! SEPrescriptionDrugsNewCell
                cell.delegate = self
                cell.update(with: viewModel.drugViewModel(at: indexPath), editEnable: viewModel.canEdit)
                return cell
            }
        case 5:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEPrescriptionDrugsNewConfirmCell.reuseIdentifier(),
                                                     for: indexPath) as! SEPrescriptionDrugsNewConfirmCell
            cell.delegate = self
            cell.update(with: viewModel)
            return cell
        default:
            return UITableViewCell()
        }
    }
}

// MARK: - UITableViewDelegate

extension SEPrescriptionNewViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == viewModel.numberOfSectionsForNew - 1 {
            return nil
        } else {
            let headerType = SEPrescriptionNewSectionHeaderType(rawValue: section) ?? .mainDiagnosis
            let header = UINib.loadViewFrom(SEPrescriptionNewSectionHeader.self)
            header.update(with: viewModel, headerType: headerType, clickHandler: { (headerType) in
                switch headerType {
                case .templateName:
                    self.pushToPrescriptionTemplateList()
                case .children:
                    self.viewModel.switchIsChildren()
                case .subDiagnosis:
                    self.viewModel.addSubDiagnosis()
                case .prescription:
                    self.presentPickDrugsVC(section)
                default: break
                }
                self.tableView.reloadData()
            })
            header.textFieldDidEndEdit = { text in
                self.viewModel.prescription.name = text
            }
            return header
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return viewModel.cellHeightForNew(at: indexPath)
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return viewModel.headerHeightForNew(in: section)
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return viewModel.footerHeightForNew(in: section)
    }
}

// MARK: - SEPrescriptionNewCellDelegate

extension SEPrescriptionNewViewController: SEPrescriptionNewCellDelegate {
    func diagnosisNewCell(_ cell: SEPrescriptionDiagnosisNewCell, didTappedWithType type: SEPrescriptionDiagnosisType) {
        view.endEditing(true)
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        presentPickDiagnosisVC(with: type, at: indexPath)
    }
    
    func diagnosisNewCell(didTappedDelete cell: SEPrescriptionDiagnosisNewCell) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        viewModel.removeSubDiagnosis(at: indexPath)
        tableView.deleteRows(at: [indexPath], with: .left)
    }
    
    func drugsNewCell(didTappedDelete cell: SEPrescriptionDrugsNewCell) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        viewModel.removeDrug(at: indexPath)
        tableView.deleteRows(at: [indexPath], with: .left)
    }
    
    func confirmCell(didTappedConfirm cell: SEPrescriptionDrugsNewConfirmCell) {
        submitPrescription()
    }
}

extension SEPrescriptionNewViewController {
    private func presentPickDrugsVC(_ section: Int) {
        let vc = SEPrescriptionPickDrugsViewController { vm in
            SELog("开处方药：\(vm.drugModel)")
            self.viewModel.insert(drug: vm.drugModel)
            self.tableView.reloadSections([section], with: .none)
        }
        vc.modalTransitionStyle = .crossDissolve
        vc.modalPresentationStyle = .custom
        present(vc, animated: true)
    }
    
    private func presentPickDiagnosisVC(with type: SEPrescriptionDiagnosisType, at indexPath: IndexPath) {
        let vc = SEPrescriptionPickDiagnosisViewController(type: type) { vm in
            self.viewModel.handleDiagnosisPick(with: type, at: indexPath, value: vm.value)
            self.tableView.reloadRows(at: [indexPath], with: .none)
        }
        vc.modalTransitionStyle = .crossDissolve
        vc.modalPresentationStyle = .custom
        present(vc, animated: true)
    }
    
    private func pushToPrescriptionTemplateList() {
        let vc = SEPrescriptionTemplateListController(isPick: true)
        navigationController?.pushViewController(vc, animated: true)
        vc.pickHandler = { id, isPick in
            self.viewModel.isPick = isPick
            self.viewModel.prescriptionMode = .template(id, false)
            self.loadData()
        }
    }
}
